﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using PreBuildGrupyz.Models;
using GrupyzServices.BdAccess;

namespace PreBuildGrupyz.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {

        // This constructor is used by the MVC framework to instantiate the controller using
        // the default forms authentication and membership providers.
        public AccountController()
            : this(null, null, new ClienteRepository())
        {
        }

        // This constructor is not used by the MVC framework but is instead provided for ease
        // of unit testing this type. See the comments in AccountModels.cs for more information.
        public AccountController(IFormsAuthenticationService formsService, IMembershipService membershipService, IClienteRepository clienterepo)
        {
            FormsService = formsService ?? new FormsAuthenticationService();
            MembershipService = membershipService ?? new AccountMembershipService();
            _clienterepo = clienterepo;
        }

        private IClienteRepository _clienterepo;

        public IFormsAuthenticationService FormsService
        {
            get;
            private set;
        }

        public IMembershipService MembershipService
        {
            get;
            private set;
        }

        protected override void Initialize(RequestContext requestContext)
        {
            if (requestContext.HttpContext.User.Identity is WindowsIdentity)
            {
                throw new InvalidOperationException("Windows authentication is not supported.");
            }
            else
            {
                base.Initialize(requestContext);
            }
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

            base.OnActionExecuting(filterContext);
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public JsonResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    //return RedirectToAction("ChangePasswordSuccess");
                    return Json(new AjaxResult
                    {
                        Mensagem = "Password actualizada com sucesso!",
                        MsgErro = "success"
                    });
                }
                else
                {
                    ModelState.AddModelError("", "A password actual está incorrecta ou a nova password é inválida.");
                }
            }

            string errors = "";
            foreach (ModelState modelState in ViewData.ModelState.Values)
            {
                foreach (ModelError error in modelState.Errors)
                {
                    errors += error.ErrorMessage;
                }
            }

            return Json(new AjaxResult
            {
                Mensagem = errors,
                MsgErro = "error"
            });
        }

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        public ActionResult LogOn()
        {
            return View();
        }

        public ActionResult EsqueceuPassword()
        {
            return View();
        }
        [HttpPost]
        public ActionResult EsqueceuPassword(FormCollection collection)
        {
            _clienterepo.ResetPassword(collection["Email"].ToString());
            return Redirect("/");
        }


        public void MigrateShoppingCart(string UserName)
        {
            // Associate shopping cart items with logged-in user
            var cart = ShoppingCart.GetCart(this.HttpContext);

            cart.MigrateCart(UserName);
            Session[ShoppingCart.CartSessionKey] = UserName;
            //Response.Cookies[ShoppingCart.CartSessionKey].Value = UserName;
        }

        [HttpPost]
        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
            Justification = "Needs to take same parameter type as Controller.Redirect()")]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    //MigrateShoppingCart(model.UserName);
                    model.UserName = Session["idUser"].ToString();

                    FormsService.SignIn(model.UserName, true);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Username ou Password incorrectos!");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult Register()
        {
            return View();
        }


        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    //MigrateShoppingCart(model.UserName);
                    model.UserName = Session["idUser"].ToString();

                    //Session["idUser"] = null;

                    FormsService.SignIn(model.UserName, true /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [Authorize]
        public ActionResult AreaPessoal(int id, int opcao = 0)
        {
            ViewData["ClienteId"] = int.Parse(HttpContext.User.Identity.Name);
            ViewData["Tab"] = opcao;
            return View(id);
        }

        [Authorize]
        public ActionResult UserInfo(int id)
        {
            return PartialView(_clienterepo.GetDadosCliente(int.Parse(HttpContext.User.Identity.Name)));
        }

        [Authorize]
        [HttpPost]
        public JsonResult UserInfo(DadosCliente dados)
        {
            if (ModelState.IsValid)
            {
                if (dados.Password == Request.Form["confPassword"] || (dados.Password == null && Request.Form["confPassword"] == "") )
                {
                    if (_clienterepo.UpdateCliente(dados, int.Parse(HttpContext.User.Identity.Name)))
                        return Json(new AjaxResult
                        {
                            Mensagem = "Dados Gravados com sucesso!",
                            MsgErro = "success"
                        });
                    else
                    {
                        ModelState.AddModelError("Email", "Este Email já existe!");
                        return Json(new AjaxResult
                        {
                            Mensagem = "Este Email já existe!",
                            MsgErro = "error"
                        });
                    }
                }
                else
                {
                    return Json(new AjaxResult
                    {
                        Mensagem = "As passwords não são identicas! Tente novamente",
                        MsgErro = "error"
                    });
                }
            }

            string errors = "";
            foreach (ModelState modelState in ViewData.ModelState.Values)
            {
                foreach (ModelError error in modelState.Errors)
                {
                    errors += error.ErrorMessage;
                }
            }

            return Json(new AjaxResult
            {
                Mensagem = errors,
                MsgErro = "error"
            });
        }


        [Authorize]
        public ActionResult Settings(int id)
        {
            return PartialView(_clienterepo.GetClienteSettings(int.Parse(HttpContext.User.Identity.Name)));
        }

        [Authorize]
        [HttpPost]
        public JsonResult Settings(SettingsViewModel dados)
        {
            if (_clienterepo.UpdateSettings(dados))
                return Json(new AjaxResult
                {
                    Mensagem = "Dados Gravados com sucesso!",
                    MsgErro = "success"
                });
            else
            {
                return Json(new AjaxResult
                {
                    Mensagem = "Erro",
                    MsgErro = "error"
                });
            }
        }


        [Authorize]
        public ActionResult Deals(int id)
        {
            var data = _clienterepo.GetComprasCliente(int.Parse(HttpContext.User.Identity.Name));
            if (data != null)
                return PartialView(data);
            else
                return PartialView("Vazio");
        }


        [Authorize]
        public ActionResult Premios(int id)
        {
            var data = _clienterepo.GetClientePremios(int.Parse(HttpContext.User.Identity.Name));
            if(data != null)
                return PartialView(data);
            else
                return PartialView("Vazio");
        }

        [Authorize]
        public ActionResult Pontos()
        {
            //Navegar para a loja
            return View();
        }


        private class AjaxResult
        {
            public string Mensagem { get; set; }
            public string MsgErro { get; set; }
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "Já existe um utilizador com este email. Por favor escolha outro email.";

                case MembershipCreateStatus.InvalidPassword:
                    return "Password inválida. Por favor escolha outra password.";

                case MembershipCreateStatus.InvalidEmail:
                    return "Email inválido. Verifique o email.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "Utilizador inválido. Tente novamente.";

                case MembershipCreateStatus.ProviderError:
                    return "Erro no serviço. Se o problema persistir contacte o D.E.G.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }

    }
}
